/**
 * 
 */
package inf.mediasManagement;

import inf.exceptions.*;
import inf.hibernateUtils.HibernateUtil;
import inf.mediasManagement.Media;
import inf.subscribersManagement.Subscriber;

import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

/** 
 * @author Fabre, Malric
 */
public class AuthorDAO {

	public static boolean add(Author author){
		Session session = HibernateUtil.openSession();
		try{
			session.saveOrUpdate(author);
		} catch (Exception e) {
			System.err.println("Problem when saving");
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static boolean remove(Author author){
		Session session = HibernateUtil.openSession();
		try{
			session.delete(author);
		} catch (Exception e) {
			System.err.println("Problem when saving");
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static Author get(long id) throws ExistsException {
		Session session = HibernateUtil.openSession();
		Author a = (Author) session.get(Author.class, id);
		if (a == null) throw new ExistsException();
		else return a;
	}

	public static boolean contains(Author author) throws ExistsException {
		Session session = HibernateUtil.openSession();
		if (author == null) throw new ExistsException();
		Author a = (Author) session.get(Author.class, author.getId());
		if (a == null) return false;
		else return a.equals(author);	
	}

	public static List<Author> getByName(String name) throws DvdExistsException {
		Session session = HibernateUtil.openSession();

		Criteria criteria = session.createCriteria(Author.class).add(Restrictions.eq("name", name));
		List<Author> authors = (List<Author>)criteria.list();

		return authors;
	}
}


